<template>
  <div class="patients-page">
    <van-nav-bar
      title="患者管理"
      left-arrow
      @click-left="router.back()"
      fixed
    />

    <!-- 搜索栏 -->
    <div class="search-bar">
      <van-search
        v-model="searchText"
        placeholder="搜索患者姓名"
        @search="onSearch"
      />
    </div>

    <!-- 患者列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div class="patient-cards">
          <van-cell-group
            v-for="patient in patients"
            :key="patient.id"
            inset
            class="patient-card"
            @click="goToDetail(patient.id)"
          >
            <van-swipe-cell>
              <van-cell center>
                <template #icon>
                  <van-image
                    round
                    width="50"
                    height="50"
                    :src="patient.avatar || defaultAvatar"
                    style="margin-right: 12px"
                  />
                </template>
                <template #title>
                  <div class="patient-info">
                    <span class="name">{{ patient.realName }}</span>
                    <span class="gender">{{ patient.gender === 1 ? '男' : '女' }}</span>
                  </div>
                </template>
                <template #label>
                  <div class="details">
                    <span>年龄：{{ patient.age || '未知' }}</span>
                    <span class="divider">|</span>

                  </div>
                </template>
              </van-cell>
              <template #right>
                <van-button
                  square
                  type="danger"
                  text="移除"
                  class="delete-button"
                  @click="handleRemove(patient)"
                />
              </template>
            </van-swipe-cell>
          </van-cell-group>
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'
import { getPatientList, removePatient } from '@/api/doctor'
import defaultAvatar from '@/assets/default-avatar.png'

const router = useRouter()
const searchText = ref('')
const patients = ref([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const current = ref(1)
const size = ref(10)

// 加载患者列表
const loadPatients = async () => {
  try {
    const res = await getPatientList({
      current: current.value,
      size: size.value,
      name: searchText.value
    })

    if (res.code === 200) {
      if (refreshing.value) {
        patients.value = []
        refreshing.value = false
      }

      const newPatients = res.data.records || []
      patients.value.push(...newPatients)

      if (patients.value.length >= res.data.total) {
        finished.value = true
      }
      current.value++
    } else {
      showToast(res.message || '获取患者列表失败')
    }
  } catch (error) {
    console.error('获取患者列表失败:', error)
    showToast('获取患者列表失败')
  } finally {
    loading.value = false
  }
}

// 移除患者
const handleRemove = async (patient) => {
  try {
    const res = await showDialog({
      title: '提示',
      message: `确定要移除患者 ${patient.realName} 吗？`,
      showCancelButton: true
    })

    if (res === 'confirm') {
      const result = await removePatient(patient.id)
      if (result.code === 200) {
        showToast('移除成功')
        // 刷新列表
        current.value = 1
        finished.value = false
        patients.value = []
        loadPatients()
      } else {
        showToast(result.message || '移除失败')
      }
    }
  } catch (error) {
    console.error('移除患者失败:', error)
    showToast('移除失败')
  }
}

// 搜索
const onSearch = () => {
  current.value = 1
  finished.value = false
  patients.value = []
  loadPatients()
}

// 下拉刷新
const onRefresh = () => {
  finished.value = false
  current.value = 1
  loadPatients()
}

// 上拉加载
const onLoad = () => {
  if (!loading.value) {
    loading.value = true
    loadPatients()
  }
}

// 跳转到患者详情
const goToDetail = (id) => {
  router.push(`/doctor/patients/${id}`)
}

onMounted(() => {
  loadPatients()
})
</script>

<style lang="scss" scoped>
.patients-page {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-top: 46px;

  .search-bar {
    position: sticky;
    top: 46px;
    z-index: 2;
  }

  .patient-cards {
    padding: 12px 0;

    .patient-card {
      margin-bottom: 12px;

      .patient-info {
        display: flex;
        align-items: center;
        gap: 8px;

        .name {
          font-size: 16px;
          font-weight: 500;
        }

        .gender {
          font-size: 14px;
          color: #666;
        }
      }

      .details {
        display: flex;
        align-items: center;
        font-size: 12px;
        color: #999;
        margin-top: 8px;

        .divider {
          margin: 0 8px;
          color: #eee;
        }
      }
    }
  }

  .delete-button {
    height: 100%;
  }
}
</style>
